var express = require('express');
var router = express.Router();
var User = require('../data/models/user');
var Product = require('../data/models/product');
var middleware = require('../middleware/middleware');



router.get('/login',function(req,res,next){
  res.render('login',{title:'login page'});
});

router.post('/loginSucc',function(req,res,next){
  var _user = {
    username: req.body.username,
    password: req.body.password
    };
  User.findOne({username: _user.username},function(err,user){
    if(err) console.log(err);
    if(!user){
      res.send('the user isnot exist');
    }else {
      if(user.password == _user.password) {
        req.session.user = _user.username;
        return res.redirect('/');
      }else {
        res.send('wrong password');
      }
    }
  });
});


router.get('/reg',function(req,res,next){
  res.render('reg',{title:'register page'});
});

router.post('/regSucc',function(req,res,next){
  var user = new User({
    username: req.body.username,
    password: req.body.password
  });
  user.save(function(err){
    if(err){
      console.log(err);
    }
    res.render('login');
  });
});

//用户退出
router.get('/logout',middleware.checkLogin);
router.get('/logout',function(req,res) {
  req.session.user = null;
  return res.redirect('/');
});

//聊天室
router.get('/chatRoom',middleware.checkLogin);
router.get('/chatRoom',function(req,res) {
  res.render('chatRoom',{
    title:'chat room'
  });
});

//个人用户中心
router.get('/center',middleware.checkLogin);
router.get('/center',function(req,res) {
  User.findOne({username:req.query.username},function(err,user) {
    if(err) {
      console.log(err);
    }
    var userTemp = user.username;
    Product.find({username:userTemp},function(err,productList) {
      if(err) {
        console.log(err);
      }
      res.render('user',{
        title: "user center",
        user: userTemp,
        prod: productList
      });
    });
  });
});

module.exports = router;